package com.xfzcode.controller;

import com.xfzcode.enums.ResultEnum;
import com.xfzcode.enums.TipsEnum;
import com.xfzcode.pojo.CommonEntity;
import com.xfzcode.result.ResponseData;
import com.xfzcode.service.ElasticsearchIndexService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author XMLee
 * @Date 2022年08月23日 22:52
 * @Description:
 */
@RestController
@RequestMapping("v1/indices")
public class ElasticsearchIndexController {

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchIndexController.class);

    @Autowired
    ElasticsearchIndexService elasticsearchIndexService;

    @PostMapping(value = "/add")
    public ResponseData addIndexAndMapping(@RequestBody CommonEntity commonEntity) {
        //构建返回数据
        ResponseData responseData = new ResponseData();
        if (!StringUtils.isNotEmpty(commonEntity.getIndexName())) {
            responseData.setResultEnum(ResultEnum.param_isnull);
            return responseData;
        }

        //添加映射是否成功
        boolean isSuccess = false;
        try {
            isSuccess = elasticsearchIndexService.addIndexAndMapping(commonEntity);
            //构建返回信息
            responseData.setResultEnum(isSuccess, ResultEnum.success, null);
            //日志记录
            logger.info(TipsEnum.create_index_success.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            logger.info(TipsEnum.create_index_fail.getMessage());
            //构建错误返回信息
            responseData.setResultEnum(ResultEnum.error);
        }
        return responseData;
    }
}
